#include "recbox.h"
#include "ui_recbox.h"

#include <cmath>
#include "recboxitem.h"

RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox)
{
    ui->setupUi(this);
}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initBoxItemUi(QJsonArray data, int row)
{
    if(row == 2)
    {
        this->row = row;
        this->col = 8; //??
    }
    else ui->recListDown->hide();

    imageList = data;

    currentIndex = 0;
    count = ceil(imageList.size() / col);

    createRecBoxItem();
}

void RecBox::createRecBoxItem()
{
    //先清除旧元素
    QList<RecBoxItem*> recUpList = ui->recLlistUp->findChildren<RecBoxItem*>();
    for(auto& e : recUpList)
    {
        ui->recListUpHLayout->removeWidget(e);
        delete e;
    }
    QList<RecBoxItem*> recDownList = ui->recListDown->findChildren<RecBoxItem*>();
    for(auto& e : recDownList)
    {
        ui->recListDownHLayout->removeWidget(e);
        delete e;
    }
    //再创建新元素
    int index = 0;
    for(int i = currentIndex * col; i < col + currentIndex * col; i++)
    {
        RecBoxItem* item = new RecBoxItem();

        QJsonObject obj = imageList[i].toObject();
        item->setText(obj.value("text").toString());
        item->setImage(obj.value("path").toString());

        if(row == 2 && index >= col / 2)
        {
            ui->recListDownHLayout->addWidget(item);
        }
        else ui->recListUpHLayout->addWidget(item);

        ++index;
    }
}

void RecBox::on_nextBtn_clicked()
{
    currentIndex++;
    if(currentIndex >= count)
    {
        currentIndex = 0;
    }
    createRecBoxItem();
}

void RecBox::on_prevBtn_clicked()
{
    currentIndex--;
    if(currentIndex <= 0)
    {
        currentIndex = count - 1;
    }
    createRecBoxItem();
}
